package org.lql.algo.codecrush.week008;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: liangqinglong
 * @date: 2025-08-18 23:57
 * @description: 15. 三数之和 <a href="https://leetcode.cn/problems/3sum/description/">...</a>
 **/
public class ThreeSum {

	public List<List<Integer>> threeSum(int[] nums) {
		List<List<Integer>> ans = new ArrayList<>();
		Arrays.sort(nums); // 排序
		int n = nums.length;
		for (int i = 0; i < n - 2; i++) {
			// 跳过重复
			if (i > 0 && nums[i] == nums[i - 1]) {
				continue;
			}
			// 剪枝
			if (nums[i] > 0) {
				break;
			}
			int l = i + 1;
			int r = n - 1;
			while (l < r) {
				int sum = nums[i] + nums[l] + nums[r];
				if (sum < 0) {
					l++;
				} else if (sum > 0) {
					r--;
				} else {
					ans.add(Arrays.asList(nums[i], nums[l], nums[r]));
					while (l < r && nums[l] == nums[l + 1]) {
						l++;
					}
					while (l < r && nums[r] == nums[r - 1]) {
						r--;
					}
					l++;
					r--;
				}
			}
		}
		return ans;
	}

	public static void main(String[] args) {
		int[] nums = new int[]{-1, 0, 1, 2, -1, -4};
		ThreeSum threeSum = new ThreeSum();
		List<List<Integer>> result = threeSum.threeSum(nums);
		System.out.println(result);
	}
}
